package com.example.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import com.example.server.SCSocketComm;
import com.example.silvercare.Coalition;
import com.example.silvercare.R;
import com.example.silvercare.Setting;
import com.example.silvercare.UserInputCheck;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import app.database.friendlist.Friend;
import app.database.friendlist.FriendListDB;

public class Notification2 extends Activity {
	EditText nameET, emailET, timeET;
	Button submitBT;
	FriendListDB dba;
	int TABLE;
	String NAME;
	String EMAIL;
	String ADDRESS;
	String TIME;
	
	String name = "";
	String email = "";
	String address = "";
	String time = "";
	
    String IpAddress;
    String Port;
    
    SharedPreferences myprefs;
    String myname;
    String myemail;
  
	final Handler UpdateHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {      
		             case 1:
		            	 Toast.makeText(Notification2.this, "Connection failed", Toast.LENGTH_SHORT).show();
		                  break;   
		             case 2:
		     			Toast.makeText(Notification2.this, "Email Address Already Exist In Database", Toast.LENGTH_SHORT).show();
		     			break;
		             case 3:
		     			nameET.setText("");
		    			emailET.setText("");
		     			Toast.makeText(Notification2.this, "Item Saved", Toast.LENGTH_SHORT).show();		
		     			break;
		              }      
		              super.handleMessage(msg);  
		         }    
		     }; 
		     
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.xml.notification2);
		
		dba = new FriendListDB(this);
		dba.open();
		
        myprefs = PreferenceManager.getDefaultSharedPreferences(this);
        myname = myprefs.getString("namePref", null);
        myemail = myprefs.getString("emailaddressPref", null);
        
		TABLE = getIntent().getIntExtra("TABLE", -1);
		NAME = getIntent().getStringExtra("NAME");
		EMAIL = getIntent().getStringExtra("EMAIL");
		ADDRESS = getIntent().getStringExtra("ADDRESS");
		TIME = getIntent().getStringExtra("TIME");
		name = NAME;
		email = EMAIL;
		address = ADDRESS;
		time = TIME;
		
		if(TABLE == -1)
		{
			Toast.makeText(this, "Table not selected in database", Toast.LENGTH_SHORT).show();
			onDestroy();
		}
		
		
		nameET = (EditText) findViewById(R.id.friendnameText);
		emailET = (EditText) findViewById(R.id.emailaddressText);
		timeET = (EditText) findViewById(R.id.timeText);
		
		submitBT = (Button) findViewById(R.id.addfriendButton);
		
		nameET.setText(name);
		emailET.setText(email);
		timeET.setText(time);
		

		//EDIT NOTIFICATION
		submitBT.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				try{
					//input check
					time = timeET.getText().toString();
					final boolean checkTime = UserInputCheck.timeCheck(time);
					if(checkTime  && !time.equalsIgnoreCase(TIME))
					{
						Toast.makeText(Notification2.this, "Don't close, Waiting for your friend response", Toast.LENGTH_SHORT).show();
						Thread bgThread = new Thread(new Runnable(){

							@Override
							public void run() {
								// TODO Auto-generated method stub
								if(modifyFriendNotification(NAME, EMAIL, ADDRESS, time))
									updateItToDB(NAME, EMAIL, ADDRESS, time, EMAIL ,TABLE);
								else{
									 Message message = new Message();      
									 message.what = 1;      
									 UpdateHandler.sendMessage(message); 
								}
							}
							
						});
						bgThread.start();
					}else
					{
						Toast.makeText(Notification2.this, "Input Invalid or Unchanged", Toast.LENGTH_SHORT).show();
						
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
		});			
	}
	
	public boolean modifyFriendNotification(String name, String email, String address, String time){
		if(getFriendConnectionInfo(email)==0)
		{
			 try {
	                Socket socket = new Socket(IpAddress,Integer.parseInt(Port));
	                //outgoing stream redirect to socket
	                message.Message msg1 = new message.Message();
	                msg1.setServiceType(3);
	                msg1.setContent(myname+"|"+myemail+"|"+address+"|"+time);
	                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
	                oos.writeObject(msg1);
	                
	                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
	                message.Message msg2 = (message.Message) ois.readObject();
	                
	                //Close connection
	                socket.close();
	                
	                if(msg2.getContent()!=null)
	                {
	                	Log.d("Tcp Example", "From server: "+msg2.getContent());
	                	if(msg2.getContent().contentEquals("OK"))
	                		return true;
	                	else
	                		return false;
	                }
	                else
	                {
	                	Log.d("Tcp Example", "From server: "+"null");
	                	return false;
	                }
	        		


		        } catch (UnknownHostException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
		        } catch (IOException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
		        } catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		return false;
		
	}
	
	//Request Ip address and port throught Coalition
	private int getFriendConnectionInfo(String email){
		String result = Coalition.getFriendConnectionInfo(email);
		if(result==null || !result.contains("|"))
			return -1;
		int mid = result.indexOf("|");
		String s1 = result.substring(0, mid);
		String s2 = result.substring(mid+1, result.length());
		if(s1 == null || s2 == null)
			return -1;
		IpAddress = s1;
		Port = s2;	
		return 0;
	}
	
	public void saveItToDB(String name, String email, String notification, String notificationTime, int table){
		if(dba.insertFriend(name, email, notification, notificationTime, table)==-1)
		{
			 Message message = new Message();      
			 message.what = 2;      
			 UpdateHandler.sendMessage(message); 

		}else
		{
			 Message message = new Message();      
			 message.what = 3;      
			 UpdateHandler.sendMessage(message); 

			dba.close();

			finish();  
		}
		/*
		if(table==0)
			startActivity(new Intent("com.example.server.FriendListActivity"));
		else if(table==1)
			startActivity(new Intent("com.example.server.TrustFriendsActivity"));*/
	}
	
	public void updateItToDB(String name, String email, String notification, String notificationTime, String oldemail, int table){
		if(dba.updateFriend(name, email,notification, notificationTime, oldemail, table)==-1)
		{
			 Message message = new Message();      
			 message.what = 2;      
			 UpdateHandler.sendMessage(message); 
		}
		else
		{
			Message message = new Message();      
			message.what = 3;      
			UpdateHandler.sendMessage(message); 
			 
			dba.close();

			finish();  
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		dba.close();
		super.onDestroy();
	}
}
